package com.dman.multi.cmd;

import java.io.IOException;
import java.net.MalformedURLException;

import org.apache.pivot.beans.BXMLSerializer;
import org.apache.pivot.collections.List;
import org.apache.pivot.util.Vote;
import org.apache.pivot.wtk.Dialog;
import org.apache.pivot.wtk.DialogStateListener;
import org.apache.pivot.wtk.Prompt;

import com.dman.multi.core.Download;
import com.dman.multi.ui.AddDownload;
import com.dman.multi.ui.DMan;

public class GUIScheduleCommand implements Command {
	
	private DMan parent = null;
	private List<Download> downloadList = null;
	private boolean cmdAdd = false;
	private AddDownload addDownload = null;
	
	public GUIScheduleCommand(DMan parent, List<Download> downloadList, boolean cmdAdd) {
		this.cmdAdd = cmdAdd;
		this.parent = parent;
		this.downloadList = downloadList;
	}

	@Override
	public void execute() {
		try {
			if(addDownload == null){
				BXMLSerializer bxmlSerializer = new BXMLSerializer();
				addDownload = (AddDownload) bxmlSerializer.readObject(AddDownload.class, "dman-add.bxml");
				addDownload.getDialogStateListeners().add(new DialogStateListener.Adapter(){
					@Override
					public Vote previewDialogClose(Dialog dialog, boolean result) {
						try {
							if(result){
								String url = addDownload.getUrl();
								String dirName = addDownload.getFolderName();
								String fileName = addDownload.getFileName();
								long startTime = addDownload.getScheduledStart();
								long stopTime = addDownload.getScheduledStop();
								Download d = new Download(dirName, url, fileName, startTime);
								d.schedule();
								if(stopTime > 0)
									d.pause(true, stopTime);
								synchronized (downloadList) {
									downloadList.add(d);
								}
							}
						} catch (MalformedURLException e) {
							Prompt.prompt("The URL is malformed, please re-enter", addDownload);
							return Vote.DENY;
						} catch (IOException e) {
							Prompt.prompt("An IO Exception occured, check if the folder chosen has privileges", addDownload);
							return Vote.DENY;
						}
						
						return Vote.APPROVE;
					}
				});

			}

			addDownload.init(cmdAdd);
			addDownload.setModal(true);
			addDownload.open(parent);
		} catch (Exception e) {
			e.printStackTrace();
			Prompt.prompt("Unable to serialize the Add download dialog. Please contact developer.", parent);
		}
	}

}
